//
//  FindViewController.swift
//  FM
//
//  Created by x on 2017/8/23.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit

class FindViewController: UIViewController {

    let titles:[String] = ["烦躁","悲伤","孤独","快乐","感动","迷茫","坐车","独处","失恋"]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    /// 初始化
    func setupUI() -> Void {
        view.backgroundColor = UIColor.white
        navigationItem.title = "发现";
        
        //1.添加collectionView
        collectionView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height-64-44)
        view.addSubview(collectionView);
        
        //添加头视图
        collectionView.addSubview(recommedView)
        
        //2.加载推荐数据
        NetWorTools.shareNetWorkTools().loadFindRecommedData(successCallBack: { (data) in
            //self.FRmdView.models  = data
            var urls:[URL] = [URL]()
            for model in data {
                if model.coverURL != nil {
                    urls.append(model.coverURL!)
                }
            }
            
            self.recommedView.models = urls
        }) { (error) in
            print("loadFindRecommndData======",error)
        }
        
        //3..加载主播数据
        NetWorTools.shareNetWorkTools().loadFindAnchorData(successCallBack: { (data) in
            self.anchors = data
            self.collectionView.reloadData()
        }) { (error) in
            print("loadFindAnchorData=======",error)
        }
        
    }
    
    
    //MARK: -- 懒加载
    
    fileprivate lazy var collectionView:UICollectionView = {
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: FindFlowLayout())
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.clear
        
        //注册cell
        collectionView.register(FindProgramCell.self, forCellWithReuseIdentifier: programTitleCellIDIdentifier)
        collectionView.register(FindAnchorCell.self, forCellWithReuseIdentifier: anchorCellIDIdentifier)
        
        //注册头视图
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: findHeadViewIDIdentifier)
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: secondHeadViewIdentifier)
        
        return collectionView;
    }()
    
    fileprivate lazy var anchors:[Radio] = [Radio]()
    
    fileprivate lazy var secondHeadView:AnchorSectionHeadView = AnchorSectionHeadView()
    
    fileprivate lazy var recommedView:RecommendView = RecommendView(frame: CGRect.init(x: 0, y:-150, width: self.view.bounds.width, height: 150))
}

/// 第一个分区的cellID
private let programTitleCellIDIdentifier = "programTitleCellIDIdentifier";

/// 第二个分区cellID
private let anchorCellIDIdentifier = "anchorCellIDIdentifier"

/// 第一个分区头视图ID
private let findHeadViewIDIdentifier = "findHeadViewIDIdentifier"

/// 第二分区头视图ID
private let secondHeadViewIdentifier = "secondHeadViewIdentifier"

extension FindViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return section == 0 ? titles.count : anchors.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.section == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: programTitleCellIDIdentifier, for: indexPath) as! FindProgramCell
            cell.index = indexPath.row+1
            cell.title = titles[indexPath.row];
            
            return cell
            
        }else {
        
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: anchorCellIDIdentifier, for: indexPath) as! FindAnchorCell
            cell.model = anchors[indexPath.row]
            
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            
        }else {
            //1.跳转界面加载详情
            let radioDetailsController = RadioDetailsViewController()
            radioDetailsController.currentRadio = anchors[indexPath.item]
            radioDetailsController.hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(radioDetailsController, animated: true)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if indexPath.section == 0 {
            let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: findHeadViewIDIdentifier, for: indexPath)
            
            view.backgroundColor = UIColor(white: 0.8, alpha: 0.7)
            let tt = UIButton(frame: CGRect.init(x: 0, y: 5, width: view.bounds.width, height: 25));
            tt.setTitleColor(UIColor(white: 0.8, alpha: 0.7), for: UIControlState.normal)
            tt.titleLabel?.font = UIFont.systemFont(ofSize: 12)
            tt.titleEdgeInsets = UIEdgeInsetsMake(0, -220, 0, 0)
            tt.backgroundColor = UIColor.white
            tt.setTitle("搜索主播/节目", for: UIControlState.normal)
            view.addSubview(tt)
            
            return view
        }else {
            let headView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: secondHeadViewIdentifier, for: indexPath)
            headView.backgroundColor = UIColor(white: 0.8, alpha: 0.7)
            secondHeadView.frame = CGRect(x: 0, y: 15, width: headView.bounds.width, height: 25)
            headView.addSubview(secondHeadView)
            
            return headView;
        }
    }
    
    /// 设置不同分区的item的大小
    ///
    /// - Parameters:
    ///   - collectionView: <#collectionView description#>
    ///   - collectionViewLayout: <#collectionViewLayout description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        //1.计算分区item的大小
        let firstSize = CGSize(width: collectionView.bounds.width/3, height: collectionView.bounds.width/3)
        let secondSize = CGSize(width: collectionView.bounds.width/2, height: 70)
        
        return indexPath.section == 0 ? firstSize : secondSize
    }

}

extension FindViewController:RecommendViewDelegate {
    //推荐按钮点击是哪个
    func btuWillClick(index: Int) {
        
    }
}

class FindFlowLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        
        scrollDirection = UICollectionViewScrollDirection.vertical
        minimumLineSpacing = 0//横向间距
        minimumInteritemSpacing = 0//垂直方向间距
        headerReferenceSize = CGSize(width: collectionView!.bounds.width, height: 40)
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.contentInset = UIEdgeInsetsMake(150, 0, 0, 0);
        
    }
}

class AnchorSectionHeadView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = UIColor.white
        setupUI()
    }
    
    func setupUI() -> Void {
        //1.添加子控件
        addSubview(bgLable)
        addSubview(titleLable)
        
        //2.布局子控件
        var cons:[NSLayoutConstraint] = [NSLayoutConstraint]()
        
        let dict = ["bgLable":bgLable,"titleLable":titleLable] as [String: Any]
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[bgLable(2)]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dict)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[bgLable]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dict)
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:[bgLable]-10-[titleLable]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dict)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[titleLable]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dict)
        
        addConstraints(cons)
        
    }
    
    //MARK: -- 懒加载
    private lazy var bgLable:UILabel = UILabel.lableWith(backgroundColor: UIColor.yellow)
    
    
    private lazy var titleLable:UILabel = UILabel.lableWith(title: "主播", titleColor: UIColor.black, fontSize: 12)
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}







